/**
 * Created by Administrator on 2017/1/5.
 */
/**
 * Created by Administrator on 2017/1/5.
 */

var pageSize = 8; //每页条数
var pageStart = 1; //当前页码
/*
	操作，添加 |  修改   |删除
		add	 modify delete
 */
var opt = "add";
var pageList;
var pageCount = 10;//总页数
/*
	查询类型：0|1|2
	0：查询所有教师信息
	1：按教师编号查询教师信息
	2：按教师姓名查询教师信息
 */
var type = 0;
var para = ""; //查询条件0
window.onload = function() {
	pageList = $('.pagination').find('a');
	setTableBTN();
//	setPageClick();
	$(".form-control").keydown(function(event) {
		if(event.keyCode == 13) {
			criteria();
			return false;
		}
	});
	/***************************************** Excel导入数据 *****************************************/
	//确认导入

	$('#fileBtn').click(function () {
	    $("#uploadimg-form").validate({
	        rules: {
	            "fileUpload": {
	                required: true,
	                accept: "xls|xlsx"
	            }
	        },
	        messages: {
	            "fileUpload": {
	                required: "",
	                accept: "文件格式不支持，请上传  xls|xlsx 文件"
	            }
	        },
	        submitHandler: function() {
	            $("#uploadimg-form").ajaxSubmit({
	                url:"/huaqiao/teacher/upload",
	                type:"post",
	                enctype:"multipart/form-data",
	                contentType: "application/json;charset=utf-8",
	                dataType:"json",
	                async:true,
	                cache:false,
	                beforeSend:function(xhr){
	                	
	                },
	                error: function(error) {
	                	alert("数据导入失败！");
	                },
	                success: function(data){
	                	alert(data);
	                },
	                complete:function(){
	                    $("#fileUpload").val("");
	                    importHide();
	                    pageStart=1;
	                    setmation();
	                }
	            });
	            return false;
	        }
	    });
	});
	$(".pagination a").eq(1).css("background-color", "#eee");
	setmation();
};
/*
	搜索事件
	按照教师姓名和编号
	0：查询所有教师信息
*/
function criteria() {
	para = $("#search").val();
	if(para != "") {
		if($.isNumeric($("#search").val())) { //按教师编号查询教师信息
			type = 1;
			para = $("#search").val();
			setmation(type, para);
		} else { //按教师姓名查询教师信息
			type = 2;
			para = $("#search").val();
			setmation(type, para);
		}
	} else {
		type = 0;
		para = $("#search").val();
		setmation(type, para);
	}
}
/*
	查询教师信息列表
 */

var setmation= function () {
	var url="/huaqiao/teacher/getByPage?type=" + type + "&para=" + para + "&pageStart=" + pageStart + "&pageSize=" + pageSize + "&time=" + new Date().getTime();
	 $.getJSON(url, function (data) {
			 var mgs = data.list;
	         var itemCount = data.itemCount;
	         $('#selectAll').prop("checked",false);//全选
	         /*
		    	设置分页参数
		    */	
//		    setPageCode(itemCount,pageList,'pc');
		    pageCount =Math.floor((itemCount + pageSize - 1) / pageSize);
		    $('#pageCount').text(pageCount);
		    
		    setTableBTN();
	        var str="";
		    for (var i = 0; i < mgs.length; i++) {
		        str += "<tr>";
		        str += "<td><input type='checkbox' name='pid' id='teacher" + i + "' value='" + mgs[i].id + "'></td>";
		        str += "<td>" + toStr(mgs[i].teacherCode) + "</td>" +
		            "<td>" + toStr(mgs[i].teacherName) + "</td>" +
		            "<td>" + toStr(mgs[i].teacherAccount) + "</td>" +
		            "<td>" + toStr(mgs[i].teacherMobile) + "</td>" +
		            //"<td>" + toStr(mgs[i].password) + "</td>" +
//		            "<td>" + toStr(mgs[i].teacherWXID) + "</td>"+
		            "<td>" + toStr(mgs[i].modifyTime) + "</td>"+
		            "<td>" + toStr(mgs[i].modifyBy) + "</td>";
		        str += "<td><a href='#' onclick=\"queryTeacherInfo('"+mgs[i].id+"')\" >查看</a>/<a href='#' onclick=\"editTeacher('modify','"+mgs[i].id+"')\">编辑</a>/<a href='#' onclick='showTeaName(" + mgs[i].id + ")'>修改密码</a></td>";
		        str += "</tr>";
		    }
		    $("#teacher_body").html(str);
	});
}

/*
	编辑教师信息
 */
function editTeacher(option, tid) {
	opt = option;
	if(opt=="add"){
		setTeacherInfo("添加老师信息",false,null);
		$('#myModal .accountInfo').css('display','inline-block');
		
	}else if(opt=="modify"){
		$('#myModal .accountInfo').css('display','none');
		$.ajax({
			type: "post",
			url: "/huaqiao/teacher/getteacher",
			data: {
				"id": tid
			},
			cache: false,
			dataType: 'json',
			success: function(mgs) {
				setTeacherInfo("编辑老师信息", false, mgs);
			},
			error: function(xhr, textStatus, errorInfo) {
				alert("未查询到符合条件的老师");
			},
			complete: function(xhr, textStatus) {}
		});
	}
}

/*
	添加老师记录
*/
function addteacher() {
	var purl = "/huaqiao/teacher/saveteacher";
	var tip = "添加";
	if(opt == "modify") {
		tip = "修改";
		purl = "/huaqiao/teacher/modifyteacher";
	}
	var tid=$('#tid').val();
	var name=$('#teachername').val();
	var mobile=$('#teacherphone').val();
	var code=$('#teachercode').val();
	var account = $('#teacheraccount').val();
	if(name=="" && mobile=="" && code==""){
		if(opt=="add"&&account==""){
			return $('#information').text("请输入相关信息");
		}
		return $('#information').text("请输入相关信息");
	}else if (name=="" || mobile=="" || code==""||(opt=="add"&&account=="")){
		return $('#information').text("请输入完整信息")
	}
	if(!(/^1[34578]\d{9}$/.test(mobile))) {
		return $('#information').text("请输入正确手机号码");
	}
	if(!(/^\d{4,6}$/.test(code))) {
		return $('#information').text("编号请输入4-6位的纯数字");
	}

	$.ajax({
		type:"post",
		url:purl,
		data:{
			id:tid,
			teacherName:name,
			teacherMobile:mobile,
			teacherCode:code,
			teacherAccount:account
		},
		success:function(mgs){
			if(opt=="add"){
				if(mgs=="0"){
					return $('#information').text("添加失败，该账号已被占用！");
				}
			}else{
				alert(tip+"成功");
			}
			pageStart=1;
			hideModel();
			setmation();
		},
		error: function() {
			alert(tip + "失败");
			hideModel();
			$('#information').text("");
			showModel(true);
		}
	});
}

/*
	删除教师信息
	弹出确认框
 */
var array = [];

function showMyAlert() {
	array = [];
	$('input[name=pid]:checked').each(function (index,element) {
        array.push(parseInt($(element).val()));
    });
    if(array.length<1){
        return alert('请至少选择一条教师记录！');
    }
    showAlert();
}
/*
	删除老师信息
*/
function delectselect() {
	$.ajax({
		type: "post",
		url: "/huaqiao/teacher/deleteteacher",
		data: {
			id: array
		},
		traditional: true,
		success: function(mgs) {
			alert("删除成功");
			hideAlert();
			pageStart=1;
			setmation(type, para);
		},
		error: function() {
			alert("删除失败");
			hideAlert();
		}
	});
}

/*
	查看一条家长信息
*/
function queryTeacherInfo(id) {
	$.ajax({
		type: "post",
		url: "/huaqiao/teacher/getteacher",
		data: {
			"id": id
		},
		cache: false,
		dataType: 'json',
		success: function(mgs) {
			setTeacherInfo("查看老师信息", true, mgs, "query");
		},
		error: function(xhr, textStatus, errorInfo) {
			alert("未查询到符合条件的老师");
		},
		complete: function(xhr, textStatus) {}
	});
}

function setTeacherInfo(title,b,mgs,info){
	if(info!=null){
		$('#myModal .ok').css('visibility','hidden');
		$('#myModal .accountInfo').css('display','inline-block');
	    $('#myModal .cancel').text("关闭");
	}else{
		$('#myModal .ok').css('visibility','visible');
	    $('#myModal .cancel').text("取消");
	}
	$('#information').text("");
	showModel(b);
	//设置弹出框标题
	$("#myModalLabel").text(title);
	//设置老师信息
	if(mgs != null) {
		$('#tid').val(toStr(mgs.id));
		$('#teachername').val(toStr(mgs.name));
		$('#teacherphone').val(toStr(mgs.mobile));
		$('#teachercode').val(toStr(mgs.code));
		$('#teacheraccount').val(toStr(mgs.account));
		/*$('#teacherpassword').val(toStr(mgs.password));*/
	}
}

function setTeacherPW(title, b, mgs, info) {

	if(info != null) {
		$('#myModal2 .ok').css('visibility', 'hidden');
		$('#myModal2 .cancel').text("关闭");
	} else {
		$('#myModal2 .ok').css('visibility', 'visible');
		$('#myModal2 .cancel').text("取消");
	}
	$('#information').text("");
	showModel2(b);
	//设置弹出框标题
	$("#myModalLabel").text(title);
	//设置老师信息
	if(mgs != null) {
		console.log(mgs);
		/*$('#tid').val(toStr(mgs.id));
		$('#teachername').val(toStr(mgs.name));
		$('#teacherphone').val(toStr(mgs.mobile));
		$('#teachercode').val(toStr(mgs.code));*/
		$("#account").val(mgs.account);
		$("#name2").val(mgs.name);
	}
}
/**
 * 修改密码
 */

var showTeaName = function(id) {
	$.ajax({
		type: "post",
		url: "/huaqiao/teacher/getteacher",
		data: {
			"id": id
		},
		cache: false,
		dataType: 'json',
		success: function(mgs) {
			setTeacherPW("修改老师密码", false, mgs, "query");
		},
		error: function(xhr, textStatus, errorInfo) {
			alert("未查询到符合条件的老师");
		},
		complete: function(xhr, textStatus) {}
	});
}

var upadteTeaPassWord = function() {
	var password = $('#password').val();
	console.log($('#password').val());
	var account = $('#account').val();
	var url = "/huaqiao/teacher/updateTeaPassWord?account=" + account + "&password=" + password;
	$.ajax({
		async: true,
		type: 'post',
		url: url,
		cache: false,
		dataType: 'json',
		contentType: 'application/x-www-form-urlencoded',
		// beforeSend:function (xhr) {$('#myModal').modal('hide');},
		beforeSend: function(xhr) {},
		success: function(data, textStatus, xhr) {
			 layer.msg("修改成功", {time: 2000});

			
			// alert(data);
			// pageNo=1;
			// showMyModel('list');
		},
		error: function(xhr, textStatus, errorInfo) {
			console.log("error");
		},
		complete: function(xhr, textStatus) {
			console.log("complete");
		}
	});
}

/***************************************** 其他函数 *****************************************/
function toStr(str) {
	return str == null ? "" : str;
}

/*-------------------------------设置分页事件开始-------------------------------------*/

//function setPageClick(){
//	pageList.each(function (index,element) {//分页点击事件
//        $(element).click(function () {
//        	pageStart = $(this).text(); 
//        	if(pageStart>Pagination.pageStart&&Pagination.pageStart==Pagination.pageCount){
//        		return alert("当前是最后一页");
//        	}else if(pageStart>Pagination.pageCount){
//            	pageStart=Pagination.pageCount;
//            }else if(pageStart==Pagination.pageStart){
//                return;
//            }
//        	setmation();
//        });
//    });
//	$(".pagination span").each(function (i) {
//        if (i == 1) {//上一页按钮
//            this.onclick = function () {
//            	pageStart=Pagination.pageStart-1;
//            	if(pageStart>Pagination.pageCount||pageStart<1||pageStart==Pagination.pageStart){
//            		return alert("当前是第一页");
//                }
//            	setmation();
//            };
//        } else if (i == 2) {//下一页按钮
//            this.onclick = function () {
//            	pageStart=Pagination.pageStart+1;
//            	if(pageStart>Pagination.pageCount||pageStart<1||pageStart==Pagination.pageStart){
//            		return alert("当前是最后一页");
//                }
//            	setmation();
//            };
//        } else if (i == 0) {
//            this.onclick = function () {
//            	pageStart=1;
//            	Pagination.pageStart==1?alert("当前是第一页"):setmation();
//            };
//        } else if (i == 3) {
//            this.onclick = function () {
//            	pageStart=Pagination.pageCount;
//            	Pagination.pageStart==Pagination.pageCount?alert("当前是最后一页"):setmation();
//            };
//        }
//    });
//}
/*-------------------------------设置分页事件结束-------------------------------------*/

/**
 	设置翻页区域按钮
 */
var setTableBTN = function() {
	$(".pagination li").each(function(i) {
		if(i == 0) { //上一页按钮
			this.onclick = function() {
				if(pageStart > 1) {
					pageStart--;

					if(pageStart < parseInt($(".pagination a").eq(1).html())) {
						$(".pagination a").eq(5).html(pageStart + 4);
						$(".pagination a").eq(4).html(pageStart + 3);
						$(".pagination a").eq(3).html(pageStart + 2);
						$(".pagination a").eq(2).html(pageStart + 1);
						$(".pagination a").eq(1).html(pageStart);
					}
					$(".pagination a").each(function(i) {
						$(".pagination a").eq(i).css("background-color", "#fff");
						if(pageStart == parseInt($(".pagination a").eq(i).html())) {
							$(".pagination a").eq(i).css("background-color", "#eee");
						}
					});

					setmation(type, para);
				} else {
					alert("当前是第一页");
				}
			};
		} else if(i == 6) { //下一页按钮
			this.onclick = function() {
				if(pageStart < pageCount) {
					pageStart++;

					if(pageStart > parseInt($(".pagination a").eq(5).html())) {
						$(".pagination a").eq(5).html(pageStart);
						$(".pagination a").eq(4).html(pageStart - 1);
						$(".pagination a").eq(3).html(pageStart - 2);
						$(".pagination a").eq(2).html(pageStart - 3);
						$(".pagination a").eq(1).html(pageStart - 4);
					}
					$(".pagination a").each(function(i) {
						$(".pagination a").eq(i).css("background-color", "#fff");
						if(pageStart == parseInt($(".pagination a").eq(i).html())) {
							$(".pagination a").eq(i).css("background-color", "#eee");
						}
					});
					setmation(type, para);
				} else {

					alert("当前是最后一页");
				}
			};
		} else { //普通翻页按钮
			this.onclick = function() {
				var index = parseInt(this.innerText);
				if(index > pageCount) {
					index = pageCount;
				}
				pageStart = index;
				$(".pagination a").each(function(i) {
					$(".pagination a").eq(i).css("background-color", "#fff");
                });
                
                $(".pagination a").eq(i).css("background-color", "#eee");
                setmation(type,para);
            }
        }
    });
};

